import { Applet } from "@/api/interface/iot";
import {
	getAppletInstance,
	marketPublish,
	marketWithdraw,
	modAppletInstance,
	upgradeInstance
} from "@/api/modules/applet/userApplet";
import PageHeader from "@/components/Frame/PageHeader";
import { Dict, DictType, getDictList, getDictObj } from "@/utils/cacheUtil";
import { AuthBtns } from "@/utils/constants";
import LoggerDialog from "@/views/system/services/components/loggerDialog";
import { PropType } from "vue";
import { useRoute } from "vue-router";
import AppletConfig from "./public/appletConfig";

import { useAuthButtons } from "@/hooks/useAuthButtons";
import "./detail.scss";
import AppletService from "./public/appletService";
import { showTips, confirm } from "@/utils/util";
import mittBus from "@/utils/mittBus";
export default defineComponent({
	setup() {
		const route = useRoute();
		const state = reactive({
			appId: route.query.appId as string,
			nodeSn: route.query.nodeSn as string,
			detail: {} as Applet.ResUserApplet
		});
		const btnList = ref([]);
		const readonly = ref(false);
		const publish = ref(false);
		const unpublish = ref(false);
		useAuthButtons(AuthBtns.appletDevelop).then((res: any) => {
			btnList.value = res.filter((item: any) => item.btnGroup);
			readonly.value = btnList.value.filter((item: any) => item.btnGroup == "1").find((item: any) => item.path == "mod")
				? false
				: true;
			publish.value = btnList.value.filter((item: any) => item.btnGroup == "7").find((item: any) => item.path == "publish")
				? false
				: true;
			unpublish.value = btnList.value.filter((item: any) => item.btnGroup == "7").find((item: any) => item.path == "unpublish")
				? false
				: true;
		});

		const init = () => {
			getAppletInstance({ id: state.appId }).then(res => {
				state.detail = res.result as Applet.ResUserApplet;
			});
		};
		const buttonsList = ref<any>([]);
		const serviceStatusLabels = ref<any>({});
		onMounted(async () => {
			buttonsList.value = [];
			serviceStatusLabels.value = await getDictObj("service_status");
			init();
		});
		const loggerDialog = reactive<any>({
			detail: {},
			title: "服务日志",
			visible: false
		});
		const submit = async () => {
			let res = await modAppletInstance({
				id: state.detail.id,
				subdomain: state.detail.subdomain,
				home: state.detail.home
			});
			let ok = showTips(res.code, "修改应用", res.message);
			if (ok) {
				init();
			}
		};
		const refresh = () => {
			mittBus.emit("refreshAppletDetail");
		};
		const changeUpgrade = async () => {
			confirm({ content: "是否安装/升级" }).then(async (flag: any) => {
				if (!flag) {
					return;
				}
				let res = await upgradeInstance({
					id: state.detail.id
				});
				let ok = showTips(res.code, "安装/升级", res.message);
				if (ok) {
					refresh();
				}
			});
		};
		const clickPublish = async () => {
			confirm({ content: "是否发布云应用" }).then(async (flag: any) => {
				if (!flag) {
					return;
				}
				const { code, message } = await marketPublish({
					appId: state.detail.appId,
					appInstanceKey: state.detail.appInstanceId.split(".")[0]
				});
				let ok = showTips(code, `发布`, message);
				if (ok) {
					refresh();
					init();
				}
			});
		};
		const clickWithdraw = async () => {
			confirm({ content: "是否下架云应用" }).then(async (flag: any) => {
				if (!flag) {
					return;
				}
				const { code, message } = await marketWithdraw({
					appId: state.detail.appId,
					appInstanceKey: state.detail.appInstanceId.split(".")[0]
				});
				let ok = showTips(code, `下架`, message);
				if (ok) {
					refresh();
					init();
				}
			});
		};
		return () => {
			return (
				<div class="applet-deploy-page">
					<PageHeader
						showBackText={false}
						v-slots={{
							operate: () => {
								return (
									<div>
										{state.detail.marketPublish == "no" ? (
											<el-link
												type="primary"
												class="ml-4 iconfont iconbx-paper-plane"
												style="width:110px"
												onClick={clickPublish}
												disabled={publish.value}
												underline={false}
											>
												发布云应用
											</el-link>
										) : (
											<el-link
												type="danger"
												class="ml-4 iconfont iconbx-reset"
												style="width:120px"
												onClick={clickWithdraw}
												disabled={unpublish.value}
												underline={false}
											>
												下架云应用
											</el-link>
										)}
										<el-button class="justify-items-end" onClick={changeUpgrade} type="primary">
											安装/升级
										</el-button>
									</div>
								);
							}
						}}
					>
						<span>
							{state.detail.appInstanceId}.{state.detail.nodeSn}
						</span>
						<el-link
							class="iconfont iconbx-sync ml-4"
							type="primary"
							onClick={() => {
								refresh();
								init();
							}}
						>
							刷新
						</el-link>
					</PageHeader>
					<LoggerDialog
						width="1024px"
						title={loggerDialog.title}
						v-model:visible={loggerDialog.visible}
						detail={loggerDialog.detail}
						footerLabel={["关闭"]}
					/>
					<el-scrollbar style="height:calc(100vh - 170px)">
						<div class="bg-white">
							{state.detail.id && (
								<AppletDomain
									detail={state.detail}
									nodeSn={state.nodeSn}
									readonly={readonly.value}
									onChange={submit}
									onRefresh={init}
									publish={publish.value}
									unpublish={unpublish.value}
								/>
							)}
						</div>
						<div class="bg-white">
							{state.detail.id && <AppletConfig detail={state.detail} nodeSn={state.nodeSn} btns={btnList.value} />}
						</div>
						<div class="bg-white">
							{state.detail.id && <AppletService detail={state.detail} nodeSn={state.nodeSn} btns={btnList.value} />}
						</div>
					</el-scrollbar>
				</div>
			);
		};
	}
});

const AppletDomain = defineComponent({
	props: {
		publish: Boolean,
		unpublish: Boolean,
		readonly: Boolean,
		nodeSn: String,
		detail: {
			type: Object as PropType<Applet.ResUserApplet>,
			default: () => {}
		}
	},
	emits: ["change", "refresh"],
	setup(props, { emit }) {
		const formEl = ref();
		const formRule = reactive({
			name: [{ required: true, message: "应用名称不能为空", trigger: "change" }]
		});

		const typeList = ref<Dict[]>([]);
		getDictList(DictType.AppletType).then(list => {
			typeList.value = list;
		});
		const changeBasic = () => {
			emit("change");
		};

		return () => {
			return (
				<>
					<div class=" shadow" style="border: 1px solid #eee;">
						{/* <div style="line-height:24px" class="flex justify-between">
							<div>
								<div class="title-left-line"></div>
								<span>应用主页</span>
							</div>
							<el-button onClick={changeBasic} type="primary">
								保存
							</el-button>
						</div> */}
						<div class="flex content-center">
							<el-form
								class="pt-4 pl-4 pr-8 grid grid-cols-2 flex-1"
								model={props.detail}
								ref={formEl}
								rules={formRule}
								disabled={props.readonly}
								label-width="100px"
							>
								<el-form-item label="应用主页" prop="home">
									<div class="flex w-full">
										<div class="flex-1">
											<el-input v-model={props.detail.home} placeholder="http://127.0.0.1:8080/index.html" />
										</div>
									</div>
								</el-form-item>
								<el-form-item label="二级域名" prop="subdomain">
									<div class="flex w-full">
										<el-input v-model={props.detail.subdomain} placeholder="二级域名">
											{{
												append: () => {
													return window.location.hostname;
												}
											}}
										</el-input>
										<el-button onClick={changeBasic} type="primary" class="ml-6">
											保存
										</el-button>
									</div>
								</el-form-item>
							</el-form>
						</div>
					</div>
				</>
			);
		};
	}
});
